<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="updateVisible"
    title="移动步骤位置"
    width="500px"
    :before-close="handleClose"
    destroy-on-close
    class="move-step-modal"
  >
    <div v-if="step" class="space-y-4">
      <!-- 当前步骤信息 -->
      <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
        <p class="text-sm text-gray-600 mb-2">
          当前步骤: <span class="font-medium text-blue-800">{{ step.description || '未知步骤' }}</span>
        </p>
        <div class="flex items-center text-xs text-blue-600">
          <span>位置: {{ step.stepNumber }} / {{ totalSteps }}</span>
          <span class="mx-2">•</span>
          <span>类型: {{ getStepTypeLabel(step.type) }}</span>
        </div>
      </div>

      <!-- 目标位置设置 -->
      <div class="flex items-center justify-between">
        <label class="block text-sm font-medium text-gray-700">目标位置:</label>
        <div class="flex items-center">
          <el-button size="small" @click="decrementPosition" :disabled="targetPosition <= 1">
            <el-icon><i-ep-minus /></el-icon>
          </el-button>
          <el-input-number 
            v-model="targetPosition" 
            :min="1" 
            :max="totalSteps"
            size="small"
            class="mx-2"
            style="width: 80px"
          />
          <el-button size="small" @click="incrementPosition" :disabled="targetPosition >= totalSteps">
            <el-icon><i-ep-plus /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 步骤列表预览 -->
      <div class="border border-gray-200 rounded-lg bg-gray-50 max-h-60 overflow-y-auto">
        <div class="p-3">
          <h4 class="text-sm font-medium text-gray-700 mb-2">步骤预览 (移动后)</h4>
          <div class="space-y-1">
            <div
              v-for="(previewStep, index) in previewSteps"
              :key="previewStep.id || index"
              class="flex items-center p-2 rounded text-sm"
              :class="getPreviewStepClass(previewStep, index)"
            >
              <div 
                class="w-5 h-5 rounded-full text-white flex items-center justify-center text-xs mr-2 font-medium"
                :class="previewStep.isMoving ? 'bg-primary' : 'bg-gray-400'"
              >
                {{ index + 1 }}
              </div>
              <el-icon 
                class="mr-2"
                :class="previewStep.isMoving ? 'text-primary' : 'text-gray-600'"
              >
                <component :is="getTypeIcon(previewStep.type)" />
              </el-icon>
              <span 
                class="flex-1"
                :class="previewStep.isMoving ? 'font-medium text-primary' : 'text-gray-700'"
              >
                {{ previewStep.description || '未知步骤' }}
              </span>
              <span v-if="previewStep.isMoving" class="text-xs bg-primary text-white px-2 py-1 rounded">
                移动目标
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 快速移动按钮 -->
      <div class="flex justify-center space-x-2">
        <el-button size="small" @click="moveToTop" :disabled="step.stepNumber === 1">
          <el-icon><i-ep-top /></el-icon>
          移至顶部
        </el-button>
        <el-button size="small" @click="moveToBottom" :disabled="step.stepNumber === totalSteps">
          <el-icon><i-ep-bottom /></el-icon>
          移至底部
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmMove"
          :disabled="targetPosition === step.stepNumber"
        >
          移动
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage } from 'element-plus'

// Element Plus 图标
import {
  Minus as iEpMinus,
  Plus as iEpPlus,
  Top as iEpTop,
  Bottom as iEpBottom,
  Link as iEpLink,
  Promotion as iEpPromotion,
  Mouse as iEpMouse,
  View as iEpView,
  Clock as iEpClock,
  Camera as iEpCamera,
  Document as iEpDocument
} from '@element-plus/icons-vue'

// Props & Emits
const props = defineProps({
  visible: Boolean,
  step: Object
})

const emit = defineEmits(['update:visible', 'confirm'])

const scriptStore = useScriptStore()

// 处理 v-model
const updateVisible = (value) => {
  emit('update:visible', value)
}

// 响应式数据
const targetPosition = ref(1)

// 计算属性
const totalSteps = computed(() => scriptStore.stepCount)

const previewSteps = computed(() => {
  if (!props.step) return []
  
  // 获取所有步骤的副本
  let steps = [...scriptStore.steps]
  
  // 找到要移动的步骤
  const movingStepIndex = steps.findIndex(s => s.stepNumber === props.step.stepNumber)
  if (movingStepIndex === -1) return steps
  
  // 移除要移动的步骤
  const [movingStep] = steps.splice(movingStepIndex, 1)
  
  // 标记移动的步骤
  movingStep.isMoving = true
  
  // 插入到新位置 (注意：targetPosition是1-based，数组是0-based)
  const newIndex = Math.max(0, Math.min(steps.length, targetPosition.value - 1))
  steps.splice(newIndex, 0, movingStep)
  
  return steps
})

// 在步骤变化时初始化位置
watch(() => props.step, (newStep) => {
  if (newStep) {
    targetPosition.value = newStep.stepNumber
  }
}, { immediate: true })

// 方法
const getStepTypeLabel = (type) => {
  const labels = {
    navigation: '页面导航',
    input: '输入文本',
    click: '点击元素',
    assertion: '验证断言',
    wait: '等待',
    screenshot: '截图'
  }
  return labels[type] || '未知类型'
}

const getTypeIcon = (type) => {
  const icons = {
    navigation: iEpLink,
    input: iEpPromotion,
    click: iEpMouse,
    assertion: iEpView,
    wait: iEpClock,
    screenshot: iEpCamera
  }
  return icons[type] || iEpDocument
}

const getPreviewStepClass = (previewStep, index) => {
  if (previewStep.isMoving) {
    return 'bg-blue-100 border border-primary'
  }
  return 'bg-white border border-gray-200'
}

const decrementPosition = () => {
  if (targetPosition.value > 1) {
    targetPosition.value--
  }
}

const incrementPosition = () => {
  if (targetPosition.value < totalSteps.value) {
    targetPosition.value++
  }
}

const moveToTop = () => {
  targetPosition.value = 1
}

const moveToBottom = () => {
  targetPosition.value = totalSteps.value
}

const confirmMove = () => {
  if (targetPosition.value === props.step.stepNumber) {
    ElMessage.info('步骤位置没有改变')
    return
  }
  
  emit('confirm', {
    step: props.step,
    fromPosition: props.step.stepNumber,
    toPosition: targetPosition.value
  })
  
  ElMessage.success(`步骤已移动到位置 ${targetPosition.value}`)
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.move-step-modal :deep(.el-dialog__body) {
  padding: 20px;
}

.rounded-button {
  border-radius: 6px;
}

/* 步骤预览动画 */
.space-y-1 > * {
  transition: all 0.3s ease;
}

/* 移动目标高亮 */
.bg-blue-100 {
  animation: highlight-pulse 1s ease-in-out infinite alternate;
}

@keyframes highlight-pulse {
  0% {
    background-color: rgb(219, 234, 254);
  }
  100% {
    background-color: rgb(191, 219, 254);
  }
}
</style>
